<template>
  <div class="app-container">
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="pd">
        <el-form-item>
          <el-input v-model="pd.yhm" placeholder="姓名"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="fetchData">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-edit" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-table
      v-loading="listLoading"
      :data="users"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row>
      <el-table-column align="center" label="用户ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="用户头像" width="160" align="center">
        <template slot-scope="scope">
          {{ scope.row.yhtx }}
        </template>
      </el-table-column>
      <el-table-column label="用户账号" width="280" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户昵称" width="280" align="center">
        <template slot-scope="scope">
          {{ scope.row.yhnc }}
        </template>
      </el-table-column>
      <el-table-column :formatter="formatScbj" pro="scbj" name="status-col" label="账户启用状态" width="210" align="center" />
      <el-table-column align="center" prop="created_at" label="修改时间" width="300">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.xgsj }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--<el-button :disabled="users.length===0" type="danger" @click="batchRemove">批量删除</el-button>-->
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="showCount"
        :page-count="totalPage"
        :total="totalResult"
        style="float:right;"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>

    </el-col>

    <!--新增界面-->
    <!-- Form -->
    <!--<el-button type="text" @click="dialogFormVisible = true">打开嵌套表单的 Dialog</el-button>-->

    <el-dialog title="新增用户" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="用户头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户昵称" :label-width="formLabelWidth">
          <el-input v-model="form.yhnc" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户账号" :label-width="formLabelWidth">
          <el-input v-model="form.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio v-model="form.yhxb" label="1">男</el-radio>
          <el-radio v-model="form.yhxb" label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="form.dhhm" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"  @click.native="submitForm" :loading="addLoading">确 定</el-button>
      </div>
    </el-dialog>

  </div>

</template>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<script>
import util from '@/common/js/util'
import { findAllUserlistPage, addUser } from '@/api/user'
export default {

  data() {
    return {
      imageUrl: '',
      currentPage: 1,
      currentResult: 0,
      entityOrField: true,
      pageStr: 'string',
      pd: {
        yhm: ''
      },
      showCount: 10,
      totalPage: 0,
      totalResult: 0,
      users: [],
      listLoading: true,

      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },


      gridData: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        username: '',
        yhnc: '',
        yhxb: '',
        yhtx: '',
        dhhm: ''

      },
      formLabelWidth: '120px'

    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 是否启用转换
    formatScbj: function(row, column) {
      return row.scbj === 1 ? '未启用' : row.scbj === 0 ? '已启用' : '未知'
    },
    formatScbjValue: function(value) {
      return value === 1 ? '未启用' : value === 0 ? '已启用' : '未知'
    },
    handleCurrentChange(currentPage) {
      console.log(`当前页: ${currentPage}`)
      this.currentPage = currentPage
      this.fetchData()
    },
    handleSizeChange(showCount) {
      console.log(`每页 ${showCount} 条`)
      this.showCount = showCount
      this.fetchData()
    },
    // 列表
    fetchData() {
      const page = {
        currentPage: this.currentPage,
        currentResult: 0,
        entityOrField: true,
        pageStr: 'string',
        pd: {
          yhm: this.pd.yhm
        },
        showCount: this.showCount,
        totalPage: 0,
        totalResult: 0
      }

      this.listLoading = true
      findAllUserlistPage(page).then(response => {
        if (response.data.reason === null) {
          this.currentPage = response.data.result.page.currentPage
          this.totalPage = response.data.result.page.totalPage
          this.totalResult = response.data.result.page.totalResult
          this.users = response.data.result.list
          // this.page = response.data.result.page
          this.listLoading = false
        } else {
          this.loading = false
          this.$message({
            message: response.data.reason.text,
            type: 'error'
          })
        }
      })
    },

    // 显示新增界面
    handleAdd: function() {
      console.log(this.addFormVisible)
      this.dialogFormVisible = true
      this.addForm = {
        name: '',
        sex: -1,
        age: 0,
        birth: '',
        addr: ''
      }
    },
    // 新增
    submitForm: function() {
      console.log("文件列表"+this.fileList);
      let self = this;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            // NProgress.start();
            console.log(this.form);
            const para = Object.assign({}, this.form)
            console.log('para', para);
            let id= this.form.id;
            if (id !== undefined && id !== null && id !== '') {//更新
              editUser(para).then((res) => {
                console.log("res");
                console.log(res);
                this.addLoading = false
                // NProgress.done();
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.$refs['from'].resetFields()
                this.fetchData()
              }).catch(function (error) {
                // 处理 getJSON 和 前一个回调函数运行时发生的错误
                self.addLoading = false;


              })
            }else {
              //新增
              addUser(para).then((res) => {
                console.log("res");
                console.log(res);
                this.addLoading = false
                // NProgress.done();
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$refs['from'].resetFields()
                this.fetchData()
              }).catch(function (error) {
                self.addLoading = false;
                console.log('发生错误！', error);


              })
            }
          })
        }
      })
    },
    //删除
    handleDel: function (index, row) {
      console.log('删除',index);
      console.log('删除row',row);
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = {
          id: row.id,
          fileurl:row.fileurl
        };
        delUser(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.fetchData();
          this.$message({
            message: '删除成功',
            type: 'success'
          });

        });
      }).catch(() => {
        this.listLoading = false;
      });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isGIF = file.type === 'image/gif';
      const isPNG = file.type === 'image/png';
      const isBMP = file.type === 'image/bmp';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      //校验成功上传文件
      if(isJPG && isLt2M == true){
        console.log(file);

        //将文件转化为formdata数据上传
        let fd = new FormData()
        fd.append('file', file)
        console.log(fd)

        // post上传图片

        let that = this

        new Promise(function (resolve, reject) {
          that.axios.post('/uploadFile', fd,
            {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }).then((response) => {
            that.imgId = response.data.data
            resolve(that.imgId);
          }).catch((error) =>{
            this.$message.error('头像上传失败，请重新上传!');
          })
        }).then(function (id){
          that.axios.get('/file/view/'+id)
            .then((response) => {
              that.imageUrl = response.request.responseURL;
            })
        })
      }

      return isJPG && isLt2M;
    }

  }
}
</script>
